<?php

namespace App\Http\Controllers\Auth;

use App\Helper\Functions;
use Illuminate\Http\Request;
use App\Http\Models\Knight;
use App\Http\Models\AgencyOrder;
use App\Http\Models\KnightApply;
use DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
use Ixudra\Curl\Facades\Curl;

class IndexController extends AuthController
{
	// 通过微信登录code登录
	public function wxCodeLogin(Request $request){

		$uChannelId = $this->COMMON_ID;
    	$uThirdInfo = $request->userInfo;
		$headUrl = $request->headUrl;
		$name = $request->name;
		$code = $request->code;

		$Functions = new Functions();
		$authHost = config('services.extend.authHost');
		$loginUrl = $authHost.'/auth/wxCodeLogin';

		$data['uChannelId'] = $uChannelId;
		$data['uThirdInfo'] = $uThirdInfo;
		$data['headUrl'] = $headUrl;
		$data['name'] = $name;
		$data['code'] = $code;
		$data['clientIp'] = $request->getclientIp();

		$newData = $Functions->Post($loginUrl, $data);

		$newData = json_decode($newData, true);
		if (isset($newData['data'])){
			// 获取骑士信息
			$Knight = new Knight();
			$knightInfo = $Knight->getInfoByUid($newData['data']['uCode']);
			$newData['knight'] = $knightInfo;

			// 获取申请信息
			$KnightApply = new KnightApply();
			$applyInfo = $KnightApply->getCurrentApplyInfo($newData['data']['uCode']);
			$newData['knightApply'] = $applyInfo;

			if (isset($newData['data']['addition']) && isset($newData['data']['addition']['uCustomInfo']) && isset($newData['data']['addition']['uCustomInfo']['csId'])){

				$csId = $newData['data']['addition']['uCustomInfo']['csId'];
//				$onlineNum = $this->getOnlineNum($csId);
//				$newData['onlineNum'] = $onlineNum;
				$newData['bannerList'] = $this->getBannerList($csId);

				$schoolInfo = DB::table('config_school')->select(['csId', 'csName', 'csTakeout', 'csShop'])->where('csId', $csId)->first();
				$newData['schoolInfo'] = $schoolInfo;

				$mobile = $newData['data']['addition']['uMobile'];
				// 获取快递员信息
				$courierInfo = DB::table('courier')->where('cMobile', $mobile)->first();
				$newData['courier'] = $courierInfo;
			}
		}

		return json_encode($newData);
    }

    // 获取首页所需信息
    public function getIndexNeedInfo($csId){

		$newData = array();
//		$onlineNum = $this->getOnlineNum($csId);
//		$newData['onlineNum'] = $onlineNum;
		$newData['bannerList'] = $this->getBannerList($csId);

		$schoolInfo = DB::table('config_school')->select(['csId', 'csName', 'csTakeout'])->where('csId', $csId)->first();
		$newData['schoolInfo'] = $schoolInfo;

		return $this->returnMsg(1, 'OK', $newData);
    }

    private function getBannerList($csId){

    	$csList = DB::table('school_banner')
    				->select(['sbId', 'sbPicture', 'sbLink', 'sbText'])
    				->where('sbEnable', 1)
    				->whereRaw('now() > sbBeginTime')
    				->whereRaw('now() < sbEndTime')
    				->where('csId', $csId)
    				->get();
    	$csList = json_decode(json_encode($csList), true);

    	$platformList = DB::table('school_banner')
    				->select(['sbId', 'sbPicture', 'sbLink', 'sbText'])
    				->where('sbEnable', 1)
    				->whereRaw('now() > sbBeginTime')
    				->whereRaw('now() < sbEndTime')
    				->where('csId', 0)
    				->get();
    	$platformList = json_decode(json_encode($platformList), true);

    	if (empty($csList)){
    		return $platformList;
    	}
    	if (empty($platformList)){
    		return $csList;
    	}

    	$resultList = array_merge($platformList, $csList);

    	return $resultList;
//  	return $this->returnMsg(1, 'OK', $returnData);
    }


    // 设置用户附加信息
	public function setUserAddition(Request $request){


		$currentInfo = $this->getUserInfoFromToken($request->token);
//	    $token = $request->token;
//	    $uSex = $request->uSex;
//	    $uCountry = $request->uCountry;
//	    $uProvince = $request->uProvince;
//	    $uCity = $request->uCity;
//	    $uSchool = $request->uSchool;
//	    $uSite = $request->uSite;
//	    $uAddress = $request->uAddress;
//	    $uCustomInfo = $request->uCustomInfo;
//
//	    $data = array();
//	    $data['token'] = $token;
//	    $data['uSex'] = $uSex;
//	    $data['uCountry'] = $uCountry;
//	    $data['uProvince'] = $uProvince;
//	    $data['uCity'] = $uCity;
//	    $data['uSchool'] = $uSchool;
//	    $data['uSite'] = $uSite;
//	    $data['uAddress'] = $uAddress;
//	    $data['uCustomInfo'] = $uCustomInfo;

//	    $returnData = $this->extendRequest('/auth/setUserAddition', $data);

		$checkAuthCode = $request->checkAuthCode;

		if($checkAuthCode){
			$uMobile = $request->uMobile;
			$authCode = $request->authCode;
			Log::info('验证手机号: '.$uMobile.'|'.$authCode);
			Log::info('Cache: '.Cache::get($uMobile));
			if (Cache::get($uMobile) != $authCode){
				return $this->returnMsg(0, '验证码不正确或已过期');
			}
			Cache::forget($uMobile);
		}

		$uCustomInfo = $request->uCustomInfo;
		if ($uCustomInfo){
			$uCustomInfo = json_decode($uCustomInfo, true);
			// 判断提交骑士信息
			if (isset($uCustomInfo['idCardUrl']) && isset($uCustomInfo['studentCardUrl'])){
				$userInfo = $this->getUserInfoFromToken($request->token);
				$Knight = new Knight();
				$knightInfo = $Knight->getInfoByUid($userInfo['uCode']);
				$knightInfo->kAdditionCheck = 0;
				$knightInfo->save();
			}
		}

		$returnData = $this->extendRequest('/auth/setUserAddition', $request->all());

		// 小程序分享
		if ($request->shareId){

			$this->addShareInfo($request->shareId, $currentInfo['uCode'], 0, 'miniapp');

//			$giftInfo = $this->getActivityStep($request->shareId, 1);
			$giftInfo = 0;
			if ($giftInfo == 0){
				// 已送过
			}else if ($giftInfo == 2){
				// 已送完
				$noticeData = array();
				$noticeData['uChannelId'] = config('services.extend.commonId');
				$noticeData['uIds'] = $request->shareId;
				$noticeData['link'] = '';
				$noticeData['first'] = '非常抱歉！苹果已送完';
				$noticeData['activityName'] = '圣诞分享活动';
				$noticeData['activityResult'] = '成功转发'.$giftInfo['stepNum'].'个新用户';
				$noticeData['activityTime'] = date('Y-m-d H:i:s', time());
				$noticeData['activitySponsor'] = '成都思先行科技';
				$noticeData['remark'] = '非常感谢参与校运通活动，下次我们会准备更多奖品，记得早点来哦！';
				$this->extendRequest('/auth/activityResultNotice', $noticeData);
			}else{
				if ($giftInfo['isSend'] == 1){
					// 送
					$noticeData = array();
					$noticeData['uChannelId'] = config('services.extend.commonId');
					$noticeData['uIds'] = $request->shareId;
					$noticeData['link'] = 'http://amg1i9a0do01p6l1.mikecrm.com/TvmcY0u';
					$noticeData['first'] = '恭喜你获得圣诞节苹果！';
					$noticeData['activityName'] = '圣诞分享活动';
					$noticeData['activityResult'] = '成功转发'.$giftInfo['stepNum'].'个新用户';
					$noticeData['activityTime'] = date('Y-m-d H:i:s', time());
					$noticeData['activitySponsor'] = '成都思先行科技';
					$noticeData['remark'] = '请点击详情填写送货地址';
					$this->extendRequest('/auth/activityResultNotice', $noticeData);
				}else{
					// 未达标
					$noticeData = array();
					$noticeData['uChannelId'] = config('services.extend.commonId');
					$noticeData['uIds'] = $request->shareId;
					$noticeData['link'] = '';
					$noticeData['first'] = '再接再厉！';
					$noticeData['activityName'] = '圣诞分享活动';
					$noticeData['activityResult'] = '已成功转发'.$giftInfo['stepNum'].'个新用户';
					$noticeData['activityTime'] = date('Y-m-d H:i:s', time());
					$noticeData['activitySponsor'] = '成都思先行科技';
					$noticeData['remark'] = '还有苹果未送完哦';
					$this->extendRequest('/auth/activityResultNotice', $noticeData);
				}
			}
		}

	    return $returnData;
    }

    // 获取用户附加信息
    public function getUserAddition($token){

    	$returnData = $this->extendRequest('/auth/getUserAddition/'.$token);

    	return $this->returnMsg(1, 'OK', $returnData);
    }

    // 用户更新订单状态
	public function affirmOrder(Request $request){

		$token = $request->token;
		$aoId = $request->aoId;
		$status = $request->status;
		$aoCancelReason = $request->chancelReason;

		$userInfo = $this->getUserInfoFromToken($token);

		$AgencyOrder = new AgencyOrder();
		$aoInfo = $AgencyOrder::find($aoId);
		if (empty($aoInfo)){
			return $this->returnMsg(0, '找不到此订单信息');
		}

		$resultInfo = $AgencyOrder->userChangeOrderStatus($userInfo['uCode'], $aoId, $status, $aoCancelReason);

		// 骑士钱包记录
		if ($status == 3 && $resultInfo['code'] === 1){
			$Knight = new Knight();
			$knightInfo = $Knight::find($aoInfo->kId);

			// 钱包增加金额
			$walletHost = config('services.extend.walletHost');
			$walletKey = config('services.extend.walletKey');

			$requestUrl = $walletHost.'/api/wallet/addTrade';

			$levelInfo = DB::table('knight_level')->where('klId', $knightInfo->klId)->first();
			$scale = (100 - $levelInfo->klFeePercent) / 100;

			$walletData = array();
			$walletData['wCode'] = $walletKey;
			$walletData['uId'] = $knightInfo->uId;
			$walletData['wtType'] = 'charge';
			$walletData['wtMoney'] = $aoInfo->aoPay * $scale;
			$walletData['wtObj'] = 'agency_order';
			$walletData['wtObjId'] = $aoId;
			$walletData['wtCustomInfo'] = '';
			$walletData['wtMemo'] = '';
			$addressInfo = $aoInfo->AgencyAddress()->first();
			$wtAbstract = $addressInfo->csName.'-'.$addressInfo->ssName.'-'.$addressInfo->aaAddress;
			$walletData['wtAbstract'] = $wtAbstract;
			$walletData['wtCode'] = $aoInfo->aoCode;

			$Functions = new Functions();
			$accountInfo = $Functions->Post($requestUrl, $walletData);
		}

		if ($status == -1 &&  $resultInfo['code'] === 1){
			// 退款
			$refundInfo = $this->refund($aoInfo->aoCode, $aoInfo->aoPay);
			return json_encode($resultInfo);
		}

		return json_encode($resultInfo);
	}

    // 退款
    public function refundMoney(Request $request){
        $aoCode = $request->aoCode;
        $refundMoney = $request->refundMoney;
        $refundReason = $request->refundReason;

        $AgencyOrder = new AgencyOrder();
        $aoInfo = $AgencyOrder::where('aoCode', $aoCode)->first();
        if (empty($aoInfo)){
            return $this->returnMsg(0, '找不到此订单信息');
        }
        if ($aoInfo->aoStatus == -1){
            return $this->returnMsg(0, '不能重复退款');
        }

        if (!$refundMoney || $aoInfo->aoPay == $refundMoney){
            $refundMoney = $aoInfo->aoPay;
        }

        // 退款
        $refundInfo = $this->refund($aoInfo->aoCode, $refundMoney);
        $refundInfo = json_decode($refundInfo, true);
        if ($refundInfo['code'] == 0){
            return json_encode($refundInfo);
        }

        if ($aoInfo->aoPay == $refundMoney){
            $AgencyOrder->userChangeOrderStatus('', $aoInfo->aoId, -1, $refundReason);
        }else{
            $AgencyOrder->userChangeOrderStatus('', $aoInfo->aoId, $aoInfo->aoStatus, $aoInfo->aoCancelReason.'|'.$refundReason);
        }

        // 通知商铺平台
        $shopHost = config('services.extend.shopHost');
        $shopRefundUrl = $shopHost.'/api/schoolTransport/order/orderRefundForXyt?order_sn='.$aoCode.'&money='.$refundMoney.'&reason'.urlencode($refundReason);
        Log::info('通知商家退款：');
        Log::info($shopRefundUrl);
        $noticeRes = Curl::to($shopRefundUrl)->get();
        Log::info($noticeRes);

        return $this->returnMsg(1, 'OK');
    }

	// 退款
	private function refund($orderId, $money, $refundReason=''){

		$payHost = config('services.extend.payHost');
		$refundUrl = $payHost.'/api/pay/refund';
		$payKey = config('services.extend.payKey');

		$data = array();
		$data['pcKey'] = $payKey;
		$data['customOrderId'] = $orderId;
        if ($refundReason == ''){
            $data['refundDesc'] = '用户订单取消';
        }else{
            $data['refundDesc'] = $refundReason;
        }

		$data['refundMoney'] = $money;
		$data['customRefundId'] = '';

		$Functions = new Functions();
		$data = $Functions->Post($refundUrl, $data);

		return $data;
	}

	// 获取学校列表
	public function getSchoolList(){
		$schoolNameList = DB::table('config_school')->where('csEnable', 1)->pluck('csName');
		$schoolIdList = DB::table('config_school')->where('csEnable', 1)->pluck('csId');

		$returnData = array();
		$returnData['nameList'] = $schoolNameList;
		$returnData['idList'] = $schoolIdList;

		return $this->returnMsg(1, 'OK', $returnData);
	}

	// 提交建议
	public function suggest(Request $request){

		$token = $request->token;
		$usContent = $request->input('content');

		if (empty($usContent)){
			return $this->returnMsg(0, '请填写建议内容');
		}

		$userInfo = $this->getUserInfoFromToken($token);

		DB::table('user_suggest')->insert([
			'uId' => $userInfo['uCode'], 'usContent' => $usContent
		]);

		return $this->returnMsg(1, '非常感谢您的支持！');
	}

	// 解析小程序密文
	public function decodeWxMiniData(Request $request){

		$token = $request->token;
    	$encryptedData = $request->encryptedData;
    	$iv = $request->iv;

    	$uChannelId = config('services.extend.commonId');

		$data = array();
		$data['token'] = $request->token;
		$data['uChannelId'] = $uChannelId;
		$data['encryptedData'] = $request->encryptedData;
		$data['iv'] = $request->iv;

		$returnData = $this->extendRequest('/auth/decodeWxMiniData', $data);

		return $returnData;
	}

	// 发送短信验证码
	public function sendSMSCode(Request $request){

		$token = $request->token;
		$mobile = $request->mobile;

		$userInfo = $this->getUserInfoFromToken($token);

		// 生成4位数随机短信验证码
		$num = rand(0, 9999).'';
		$length = strlen($num);
		for($i=0;$i<(4-$length);$i++){
			$num = '0'.$num;
		}

		// 生成请求网址
		$host = config('services.extend.smsHost');
		$key = config('services.extend.smsKey');
		$url = $host.'/api/ability/sendSMS/'.$key.'/'.$mobile.'/'.$num;

		// 存储信息
//		$request->session()->put($mobile, $num);
//		Log::info('存储session: '.$mobile.':'.$request->session()->get($mobile));
//		$request->session()->flash($mobile, $num);

		Cache::add($mobile, $num, 10); //十分钟内有效
		Log::info('cache存储: '.$mobile.':'.Cache::get($mobile));

		// 请求发送短信
		$Functions = new Functions();
		$returnData = $Functions->Get($url);

		return $returnData;
	}

	// 获取七牛云上传token
	public function getQiniuTokenInfo($token){

		$userInfo = $this->getUserInfoFromToken($token);

		$host = config('services.extend.uploadHost');
		$key = config('services.extend.uploadKey');

		$uId = $userInfo['uCode'];
		$url = $host."/api/ability/getQiniuTokenInfo/{$key}/{$uId}";

		// 请求发送短信
		$Functions = new Functions();
		$returnData = $Functions->Get($url);

		return $returnData;
	}

	// 添加分享信息
	public function addShareInfo($shareId, $uId, $caId, $ushChannel=''){
		$shareInfo = DB::table('user_share')->where('ushShareId', $shareId)->where('uId', $uId)->first();
		if (empty($shareInfo)){
			DB::table('user_share')->insert(['ushShareId'=>$shareId, 'uId'=>$uId, 'caId'=>$caId, 'ushChannel'=>$ushChannel]);
		}
	}

	public function getActivityStep($shareId, $caId){

		$giftNum = DB::table('activity_send_log')->where('uId', $shareId)->where('caId', $caId)->count();
		if ($giftNum > 0){
			return 0;
		}

		$resultInfo = array();
		$resultInfo['isSend'] = 0;
		$resultInfo['stepNum'] = 0;

		$stepNum = DB::table('user_share')->where('ushShareId', $shareId)->where('caId', $caId)->count();

		$activityInfo = DB::table('activity_gift_graded')->where('aggEnable', 1)->where('caId', $caId)->first();
		// 判断奖品是否发完
		if ($activityInfo->aggLv1Total > $activityInfo->agglv1Send){
			// 判断是否达到难度等级
			if ($stepNum >= $activityInfo->agglv1Difficulty){
				$resultInfo['isSend'] = 1;
				$resultInfo['stepNum'] = $stepNum;
				$this->addSendLog(1, $shareId, $caId);
			}else{
				$resultInfo['isSend'] = 0;
				$resultInfo['stepNum'] = $stepNum;
			}
			return $resultInfo;
		}

		if ($activityInfo->aggLv2Total > $activityInfo->agglv2Send){
			// 判断是否达到难度等级
			if ($stepNum >= $activityInfo->agglv2Difficulty){
				$resultInfo['isSend'] = 1;
				$resultInfo['stepNum'] = $stepNum;
				$this->addSendLog(2, $shareId, $caId);
			}else{
				$resultInfo['isSend'] = 0;
				$resultInfo['stepNum'] = $stepNum;
			}
			return $resultInfo;
		}

		if ($activityInfo->aggLv3Total > $activityInfo->agglv3Send){
			// 判断是否达到难度等级
			if ($stepNum >= $activityInfo->agglv3Difficulty){
				$resultInfo['isSend'] = 1;
				$resultInfo['stepNum'] = $stepNum;
				$this->addSendLog(3, $shareId, $caId);
			}else{
				$resultInfo['isSend'] = 0;
				$resultInfo['stepNum'] = $stepNum;
			}
			return $resultInfo;
		}

		return 2;
	}

	// 添加发放奖品记录
	private function addSendLog($lv, $uId, $caId, $csId=0){

		DB::table('activity_gift_graded')->where('caId', $caId)->increment('agglv'.$lv.'Send');

		DB::table('activity_send_log')->insert(['caId' => $caId, 'uId' => $uId]);
	}

	// 获取用户公众号渠道二维码
	public function wxQrCode(Request $request)
    {
        $code = $request->code;

		if (Cache::has($code)){
			$info = Cache::get($code);

			$openId = $info['openid'];

			$authHost = config('services.extend.authHost');
			$getUrl = $authHost.'/auth/getUserQrCode/' . $openId;
			$qrInfo = Curl::to($getUrl)->get();
			$qrInfo = json_decode($qrInfo, true);
			return redirect('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$qrInfo['data']['wpuQRTicket']);
		}

        if ($code) {

			//获取用户信息
			$info = $this->getInfo($code);
			if (!isset($info['openid'])){
				print_r($info);exit;
			}

			Cache::put($code, $info, 1);
            //更新获取的最新信息到用户表
//			exit;
//			foreach($info as $k=>$v){
//				echo $k."=>".$v."<br />";
//			}
//			exit;

			$openId = $info['openid'];

			$authHost = config('services.extend.authHost');
			$getUrl = $authHost.'/auth/getUserQrCode/'.$openId;
			$qrInfo = Curl::to($getUrl)->get();
//			print_r($qrInfo);exit;
			$qrInfo = json_decode($qrInfo, true);
			if ($qrInfo['code'] == 1){
				return redirect('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$qrInfo['data']['wpuQRTicket']);
			}else{
				return $qrInfo['msg'];
			}
       }
    }

    /**
     * 通过code换取网页授权access_token
     *
     * @return mixed
     */
    private function getInfo($code)
    {
    	$appId = 'wx8ab9feb80f4bc7e4';
        $secret = '488dd10ac2ba499ba30559b8b16c4f5d';

        $data = Curl::to('https://api.weixin.qq.com/sns/oauth2/access_token')
            ->withData(['appid' => $appId, 'secret'=> $secret, 'code' => $code, 'grant_type' => 'authorization_code'])
            ->get();

//		{ "access_token":"ACCESS_TOKEN",
//		"expires_in":7200,
//		"refresh_token":"REFRESH_TOKEN",
//		"openid":"OPENID",
//		"scope":"SCOPE" }
//		print_r($data);exit;
        $data = json_decode($data, true);

//      //重新设置缓存，有效期120分钟
//      Cache::put('access_token', $curl['access_token'], 120);

        return $data;
    }

    // 添加商家（公众号分组）
    public function addMerchant($wpgCode){

    	$authHost = config('services.extend.authHost');
    	$url = $authHost."/auth/addPublicGroup/{$wpgCode}/1";

    	$data = Curl::to($url)->get();

    	return $data;
    }

}
